package websocket.piggy;

import com.alibaba.fastjson2.JSONObject;
import javax.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

@ClientEndpoint
public class WebsocketSourceClient {

    private final Session serveToModel;
    private final Session h5toServer;

    public WebsocketSourceClient(Session h5toServer) throws URISyntaxException, DeploymentException, IOException {
        WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer();
        serveToModel = webSocketContainer.connectToServer(this, new URI("wss://ai.bobfintech.com.cn/multimodal/dangjian/asr/asr_online"));
        this.h5toServer = h5toServer;
    }

    public Session getServeToModel() {
        return serveToModel;
    }

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Tomcat Client Connect Server");
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        JSONObject jsonObject = JSONObject.parseObject(message);
        System.out.println("Tomcat Client received message: " + jsonObject);
        h5toServer.getBasicRemote().sendText(jsonObject.toString());
    }

    @OnClose
    public void onClose(Session session) throws IOException {
        session.close();
        System.out.println("Tomcat Client disconnected!");
    }
}
